<template>
    <view class="content ">
        <van-nav-bar :title="scrolling? navBarTitle : '' " left-arrow @click-left="onClickLeft"> </van-nav-bar>
        <scroll-view :refresher-enabled="false" class="scroll-content" scroll-y @scroll="scrollPage" show-scrollbar="false">
          <!-- <loading :loadingIsShow="loadingIsShow" v-if="!isrefresher"></loading> -->
          <view class="bgCart">
              <view class="cartTop">
                  <view class="cartAd">
                      <view class="cartAd_title">购物结算</view>
                  </view>
                  <template v-if="source!==SOURCE_TYPE.SERVICE">
                    <view class="userInfo">
                        <view class="userInfo_left" v-if="ebUserAddressList.length>0">
                            <view class="user_address" @click="changeAddress(1)">
                                <view class="user_address_text">{{ receivingAddress.houseNumber }}</view>
                                <van-icon name="arrow" size="11" style="margin-left:10px ;" />
                            </view>
                            <view class="userInfo_bottom">
                                <text class="userName" style="margin-right: 10px;">{{ receivingAddress.realName }}</text>
                                <text class="userTel">{{ receivingAddress.phone }}</text>
                            </view>
                        </view>
                        <view class="userInfo_left" v-else>
                            <view class="user_address" @click="changeAddress(0)">
                                <text>请先选择地址再进行结算</text>
                                <van-icon name="arrow" size="11" style="margin-left:10px ;" @click="changeAddress(0)" />
                            </view>
                        </view>
                        <view class="userInfo_right deliveryMethod">
                            <view class="tab-bar gray">
                                <view
                                    class="tabbar-item"
                                    v-for="(item, index) in tabBarList"
                                    @click="changeTab(index, $event, item.name)"
                                    :class="{ active: index === currentIndex }"
                                    :key="index">
                                    {{ item.name }}
                                </view>
                            </view>
                        </view>
                    </view>
                  </template>
                  <template v-else>
                    <view class="userInfo">
                        <view class="userInfo_left">
                            <view class="userInfo_bottom">
                                <text class="userName" style="margin-right: 10px;">{{ nickName }}</text>
                                <text class="userTel">{{ phone }}</text>
                            </view>
                        </view>
                        <!-- <view class="userInfo_left" v-else>
                            <view class="user_address">
                                <text @click="toastMsg">请先选择地址再进行结算</text>
                                <van-icon name="arrow" size="11" style="margin-left:10px ;" @click="changeAddress(0)" />
                            </view>
                        </view> -->
                    </view>
                  </template>
              </view>
              <template v-if="source!==SOURCE_TYPE.SERVICE">
                  <!-- <view class="line" v-if="ebUserAddressList.length>0"></view> -->
                  <!-- 选择自提并且 地址不为空 -->
                  <template v-if="ebUserAddressList.length > 0 && currentIndex===0">
                      <!-- 有自提点 -->
                      <view class="cart_content self-pickup " v-if="merchantList.length > 0">
                          <view class="self-pickup-left" @click="toSelectPick">
                              <view class="self_pickup_pic"> <img :src="foundEleMerchant.imgUrl ? foundEleMerchant.imgUrl:'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/zitiPic.png'" alt="" mode="widthFix"> </view>
                              <view class="self_pickup_left_l">
                                  <view class="left_top"> <text class="self_pickup_name">{{foundEleMerchant.merchantName || '加载中...'}}</text><text class="distance" >距离{{ distance }}</text> </view>
                                  <view class="left_bottom">营业时间：{{ foundEleMerchant.businessHours }}</view>
                              </view>
                          </view>
                          <view class="self-pickup-right" v-if="foundEleMerchant"  @click="toMap(foundEleMerchant)">
                              <img
                                  src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/self_pickup.png"
                                  alt=""
                                  style="width: 16px; height: 16px;">
                              <view class="spr_text">当前自提点</view>
                          </view>
                      </view>
                      <!-- 无自提点 -->
                      <view class="cart_content self-pickup " v-else>
                          <view class="no-self-pickup"> 当前小区暂无自提点 </view>
                      </view>
                  </template>
                  <!-- 同城配送 -->
                  <template v-if="currentIndex===1">
                    <!-- <view class="cart_content self-pickup city_delivery_content">
                        <view class="city_delivery_content_left" style="width: 85%;">
                            <view class="left_top"> 立即配送，约10:32送达 </view>
                            <view class="left_bottom">商家等待您的下单</view>
                        </view>
                        <view class="city-delivery" style="width: 15%;">
                          <view class="city_delivery_pic" > <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/submitOrder.png" alt="" mode="widthFix"> </view>
                        </view>
                    </view> -->
                    <logisticsTimelinessInfo :type="'settlement'"></logisticsTimelinessInfo>
                  </template>
              </template>
              <!-- 彩色的线 -->
              <view class="clearfix">
                  <img src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/colorLine.png"  alt="" style=" display:block; width: 100%; height:3px;" />
              </view>

              <view class="cartList">
                  <template v-if="source!==SOURCE_TYPE.SERVICE">
                    <view class="goodsWraper clearfix" v-for="(item,index) in productList" :key="index" :id="item.Id">
                        <view class="wraper_left">
                            <view class="goodsPic"> <img class="img" :src="item.productUrl" mode="widthFix" /> </view>
                            <view class="goodsText">
                              <view class="goodsText_top">
                                  <view class="goodsTop">
                                      <view class="goods_T">{{ item.productName }}</view>
                                      <view class="goods_price">X {{ item.cartNum }}</view>
                                  </view>
                                  <view class="goods_specs" @click.stop="showSpecs()">{{ item.productAttrValueName }} </view>
                              </view>
                                <view class="goodsBottom">
                                    <view class="money">￥{{ item.price }}</view>
                                    <view class="jifen_box"> <view class="money">最多可用</view>
                                        <img
                                            src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                            alt=""
                                            style="height: 22rpx; width: 22rpx; margin-right: 6px;margin-left: 6px;" />
                                        {{ item.maxUsefulIntegrals }}
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                  </template>
                  <template v-else>
                    <view class="goodsWraper clearfix">
                        <view class="wraper_left">
                            <view class="goodsPic">
                                <img class="img" :src="serviceProductDetail.productUrl" mode="widthFix" />
                            </view>
                            <view class="goodsText">
                              <view class="goodsText_top">
                                  <view class="goodsTop">
                                      <view class="goods_T">{{ serviceProductDetail.productName }}</view>
                                      <view class="goods_price">X {{ serviceProductDetail.buyNum }}</view>
                                  </view>
                                  <view class="goods_specs" @click.stop="showSpecs()">{{ serviceProductDetail.productSpecName}} </view>
                              </view>
                                <view class="goodsBottom">
                                    <view class="money">￥{{ serviceProductDetail.price }}</view>
                                    <view class="jifen_box"> <view class="money">最多可用</view>
                                        <img
                                            src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                            alt=""
                                            style="height: 22rpx; width: 22rpx; margin-right: 6px;margin-left: 6px;" />
                                        {{ serviceProductDetail.maxUsefulPoints }}
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                  </template>
              </view>

              <view class="price_detail clearfix">
                  <view class="price_detail_title">价格明细</view>
                  <view class="price_detail_content">
                      <!-- 价格总额 -->
                      <view class="price_detail_box all">
                          <view class="price_detail_name">商品总额</view>
                          <view class="price_detail_num num">￥{{totalAmount}}</view>
                      </view>
                      <!-- 运费 -->
                      <view class="price_detail_box freightAmount" v-if="source!==SOURCE_TYPE.SERVICE">
                          <view class="price_detail_name">运费</view>
                          <view class="price_detail_num num" v-if="currentIndex===1">￥{{ freightAmount }}</view>
                          <view class="price_detail_text" v-if="currentIndex===0">免运费</view>
                      </view>
                      <!-- 优惠活动 -->
                      <view class="price_detail_box couponAct" v-if="totalThresholdAmount && totalThresholdAmount > 0 && totalFullDiscount>0">
                          <view class="price_detail_top">
                              <view class="price_detail_name">优惠活动</view>
                              <view class="price_detail_tips">满{{totalThresholdAmount}}减{{totalFullDiscount}}</view>
                          </view>
                          <!-- totalDiscount -->
                          <view class="price_detail_num num_o">- ￥{{ totalFullDiscount }}</view>
                      </view>
                      <!-- 优惠券 -->
                      <view class="price_detail_box coupon" v-if="ebStoreCouponList.length > 0">
                          <view class="price_detail_top">
                              <view class="price_detail_name">优惠券</view>
                              <view class="price_detail_tips"> {{defaultBestCoupon.money}}元{{ defaultBestCoupon.useType === 1? '全场通用券' : defaultBestCoupon.useType === 2? '商品券' : '品类券'  }}</view>
                          </view>
                          <view @click="openMyCoupon" class="price_detail_num num_o">-￥{{defaultBestCoupon.money}} <van-icon name="arrow" size="12" style="margin-left:5px ;" /></view>
                      </view>
                  </view>
                  <!-- payment 支付方式 -->
                  <view class="payment">
                      <view class="payment_top">
                          <view class="payment_left price_detail_name">支付方式</view>
                          <view class="payment_right  price_detail_name" @click="openPayment(integralsBalance,orderMaxUsefulIntegrals)">支付
                            <span class="payment_num">
                              <span  v-if="shouldShowIntegrals"> <img
                                  src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                  alt=""
                                  style="height: 13px; width: 13px;margin-left: 11px; margin-right: 6px;"/>
                              {{ useIntegrals}}  </span> <span v-if="shouldShowPlus">+</span> <span v-if="shouldShowCash">￥{{ useCash }}</span></span>
                              <van-icon name="arrow" size="12" style="margin-left:5px ;"/>
                          </view>
                      </view>
                      <view class="payment_left_bottom price_detail_tips"> 我的积分:
                          <img
                              src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/jinbi_gray1127.png"
                              alt=""
                              style="height: 10px; width: 10px;margin-left: 5px; margin-right: 5px;">
                          {{ integralsBalance }}
                      </view>
                  </view>
              </view>
              <template v-if="source!==SOURCE_TYPE.SERVICE">
                <view class="nav_box" style="height: 72px;">
                    <van-submit-bar
                        :price="allPrice" button-text="提交订单"
                        @submit="onClickButton" button-type="warning"
                        :loading="isSubmitting"
                        :disabled="isSubmitting || ebUserAddressList.length==0 || (ebUserAddressList.length>0 && merchantList.length ==0&& currentIndex===0)" :class="{'disabledSubmit':isSubmitting,'disabledSubmit':ebUserAddressList.length==0 || (ebUserAddressList.length>0 && merchantList.length ==0&& currentIndex===0)}" >
                        <view class="footContent">
                            <view class="payment_num" style="line-height: 14px;"> <span v-if="shouldShowIntegrals"><img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                alt=""
                                style="height: 13px; width: 13px; margin-right: 6px;" /> {{useIntegrals}}</span> <span v-if="shouldShowPlus"  style="margin-left: 6rpx; margin-right: 6rpx;">+</span> <span v-if="shouldShowCash"> ¥{{useCash}}</span></view>
                            <view class="price_detail_tips" style="line-height: 14px;" v-if="totalReductionAmount && totalReductionAmount > 0"> 共减￥ {{totalReductionAmount}}</view>
                        </view>
                    </van-submit-bar>
                    <!-- <van-submit-bar :price="allPrice" button-text="提交订单" disabled v-else class="disabledSubmit">
                        <view class="footContent">
                          <view class="payment_num" style="line-height: 14px;"> <span v-if="shouldShowIntegrals"><img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                alt=""
                                style="height: 13px; width: 13px; margin-right: 6px;" /> {{useIntegrals}}</span> <span v-if="shouldShowPlus">+</span> <span v-if="shouldShowCash"> ¥{{useCash}}</span></view>
                            <view class="price_detail_tips" v-if="totalReductionAmount && totalReductionAmount > 0"> 共减￥{{totalReductionAmount}} </view>
                        </view>
                    </van-submit-bar> -->
                </view>
            </template>
            <template v-else>
                <view class="nav_box" style="height: 72px;">
                    <van-submit-bar
                        :price="allPrice"
                        button-text="提交订单"
                        @submit="submitServiceOrder"
                        button-type="warning"
                        :disabled="isSubmitting" :class="{disabledSubmit:isSubmitting}" >
                        <view class="footContent">
                            <view class="payment_num" style="line-height: 14px;"> <span v-if="shouldShowIntegrals"><img
                                src="https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/shangcheng/jinbi.png"
                                alt=""
                                style="height: 13px; width: 13px; margin-right: 6px;" /> {{useIntegrals}}</span> <span v-if="shouldShowPlus" style="margin-left: 6rpx; margin-right: 6rpx;"> + </span> <span v-if="shouldShowCash"> ¥ {{ useCash}}</span></view>
                            <view class="price_detail_tips" style="line-height: 14px;" v-if="totalFullDiscount && totalFullDiscount > 0"> 共减￥ {{totalFullDiscount}}</view>
                        </view>
                    </van-submit-bar>
                </view>
            </template>
          </view>
        </scroll-view>
        <van-toast id="van-toast" />
        <myCoupon :show="myCouponShow" @closeCoupon="closeMyCoupon" @submitCoupon="submitCoupon" :ebStoreCouponResponse="ebStoreCouponResponse" :defaultBestCoupon="defaultBestCoupon"></myCoupon>
        <myHouse :show="myHouse" :house="house" @closeHouse="closeMyHouse" :newAddressId="newAddressId" :pageBiaoshi="pageBiaoshi" :ebUserAddressList="ebUserAddressList" :wxUserBaseInfo="wxUserBaseInfo" :addressInfo="receivingAddress"></myHouse>
        <paymentPopup :show="paymentShow" @closePayment="closePayment" :popupCash="popupCash" :needPayCashAmount="needPayCashAmount" :popupUseIntegrals="popupUseIntegrals" :myIntegralsBalance="integralsBalance" :maxScore="orderMaxUsefulIntegrals" :exchangeRate="exchangeRate" @confirm="handlePaymentConfirm" ></paymentPopup>
    </view>
</template>

<script>
import Toast from '@/wxcomponents/vant/toast/toast'
import myCoupon from '@/mycomponents/shangcheng/myCoupon.vue'
import myHouse from '@/mycomponents/myHouse.vue'
import paymentPopup from '@/mycomponents/shangcheng/paymentPopup.vue'
import { SOURCE_TYPE } from '@/utils/constant'
import loading from '@/mycomponents/loading.vue'
import { getCartSettlementApi,getOrderFreightApi,creatOrderApi,getMerchantListApi,changeCouponAndGetResultApi,directBuyApi} from '@/api/shoppingCart'
import { queryServiceSettleInfoApi,createServiceOrderApi } from '@/api/order'
import logisticsTimelinessInfo from '@/mycomponents/shangcheng/logisticsTimelinessInfo.vue'
import {getUserAddressApi} from '@/api/mine'

export default {

    components: {
      myCoupon,
      myHouse,
      paymentPopup,
      loading,
      logisticsTimelinessInfo
    },
    name: 'Cart',
    data() {
      return {
        isrefresher: false,
        loadingIsShow: true,
        loadingIsShowPage: true,
        SOURCE_TYPE: SOURCE_TYPE,  // 将导入的常量添加到 data 中使其成为响应式
        navBarTitle: '购物结算',
        scrolling: false, // 顶部区域吸顶效果
        wxUserBaseInfo: {},  //微信用户信息
        ebUserAddressList: [], //用户地址
        receivingAddress: null,  //用户默认地址
        houseName: '金鑫·滨湖一号3号楼1单元201',
        showHouseName: false, // 切换房子的列表
        myHouse: false,
        house: 0, // 有无房屋
        currentIndex: 0, // 配送方式的tab
        tabBarList: [
          {
            name: '自提',
            key: 'ziti'
          },
          {
            name: '同城配送',
            key: 'tongcheng'
          }
        ],
        nickName: '王彤美',
        phone: '15236236547',

        selfPickupName: '有',
        merchantList: [], //商户列表
        foundEleMerchant: null, //用户信息
        distance: undefined, //距离
        productInfoList: [], //提交商品信息列表
        productList: [], //实物商品列表
        serviceProductDetail: null, //服务商品列表
        myCouponShow: false, // 优惠券弹窗
        ebStoreCouponResponse: {}, //优惠券信息
        ebStoreCouponList: [], //用户拥有的可用优惠券列表
        defaultBestCoupon: null, //默认最优优惠券
        paymentShow: false, // 支付方式选择弹窗
        freightAmount: '0',
        score: '0', // 需要支付的积分
        needPayCashAmount: '0', // 需要支付的金额            
        integralsBalance: '0', // 我的积分
        orderMaxUsefulIntegrals: "0", //订单最大可用积分数
        useIntegrals: '0', //实际使用积分
        useCash: '0', //实际使用的现金
        popupCash: '0', //弹出的现金 //第一个框  固定的现金
        popupUseIntegrals: '0', //弹出的积分  //第一个框  固定的积分 
        finalOrderAmount: '0', //最终订单金额 扣掉满减  去掉优惠
        frontCalAmount: '0', // 前计算金额
        usedCouponAmount: '0', //使用优惠券的金额
        totalAmount: undefined, //商品总额
        totalReductionAmount: undefined, //总减免金额
        pageBiaoshi: 'settlement',
        prouductIdList: undefined, //支付页面shangpinID  购物车ID列表
        totalThresholdAmount: undefined, //满多少 减多少  总满金额
        totalFullDiscount: undefined, //总减金额 （优惠的金额)） 服务商品底部需要用
        totalAdditionalAmount: undefined, //总凑得金额
        totalDiscount: undefined,
        nearestDistanceMap: undefined,
        loading: true,
        exchangeRate: '10', //兑换率
        productType: 0, //商品类型 0 实物商品 1 服务商品
        payType: null, //支付方式// 现金支付 CASH("1"), // 积分支付 POINTS("2"), // 现金+积分支付 CASH_POINTS("3");
        productInfo: null,
        couponProductInfoList: null, //提交优惠券时商品信息列表
        productMatchedCouponInfo: null,// 商品匹配优惠券信息
        discountedAmount: '0',
        isSubmitting: false, // 新增防抖状态
        debounceTimer: null, // 防抖计时器
        params: null,
        source: undefined, // 从购物车页面跳转过来
        addressId: undefined, // 地址ID
        serviceFullDiscountId: undefined, //服务商品满减ID
        pointsDeductAmount: '0', //积分抵现金额
        newAddressId: undefined, //新地址ID
        pointToAmountExceed: 0, //积分抵现金额是否超过商品金额
        isDefaultSubmit:1, // 是否默认提交的数据(0=不是(修改优惠券，修改积分) 1=是(什么都没修改))
      }
    },

    computed: {
      shouldShowIntegrals() {
        return Number(this.useIntegrals) > 0 && Number(this.integralsBalance) > 0;
      },
      shouldShowCash() {
        return this.useCash > 0;
      },
      shouldShowPlus() {
        return this.shouldShowIntegrals && this.shouldShowCash;
      },
      canSubmit() {
        return this.ebUserAddressList.length > 0 &&
          this.selfPickupName &&
          this.useCash >= 0 &&
          !isNaN(this.useCash);
      },
      numericMaxPoints() {
        return Math.min(
          Number(this.orderMaxUsefulIntegrals),
          Number(this.integralsBalance),
          Math.floor(Number(this.popupCash) * this.exchangeRate)
        );
      },
    },

    watch: {
        foundEleMerchant: {
          handler(newVal) {
            console.log('商户信息更新:', newVal);
            this.$forceUpdate(); // 强制更新视图
          },
          deep: true
        }
    },
    onLoad(data){
      // const eventChannel = this.getOpenerEventChannel();
      // // 监听自提点更新事件
      // eventChannel.on('updateSelfPickup', (data) => {
      //   if (data.selectedMerchant) {
      //     this.foundEleMerchant = data.selectedMerchant;
      //     console.log('更新自提点----', data.selectedMerchant,data)
      //   }
      // });
       // 取到路由携带的参数
       if (data && data.params) {
            this.params = JSON.parse(decodeURIComponent(data.params))
            console.log(JSON.parse(decodeURIComponent(data.params)))
            console.log('params', this.params)
            this.prouductIdList = this.params.cartIds
            this.source = this.params.source || SOURCE_TYPE.DEFAULT
        }

    },

    onReady () {
       this.onRefresherMethod()
    },

    onShow(){
       // 监听自定义事件
       uni.$on('selfPickupUpdate', (merchant) => {
            console.log('自提点已更新:', merchant);
            if(merchant) {
                this.foundEleMerchant = merchant;
                console.log('自提点已更新:', merchant,merchant.merchantName);
            }
        });
         // 新增：判断是否从addAddress页面返回
        const fromAddAddress = uni.getStorageSync('fromAddAddress');
        this.newAddressId = uni.getStorageSync('newAddressId');
        if (fromAddAddress) {
            // 清除标记，避免重复触发
            uni.removeStorageSync('fromAddAddress');
            uni.removeStorageSync('newAddressId');
            // 刷新结算数据
            this.onRefresherMethod(fromAddAddress);
            // 打开地址选择弹窗
            this.myHouse = true;
        }
    },
    onUnload() {
        // 移除事件监听
        uni.$off('selfPickupUpdate');
    },
    methods: {
      onRefresherMethod(isFromAddAddress) {
          if (this.source !== SOURCE_TYPE.SERVICE){
              this.getUserAddressList(this.newAddressId)
          }
          if(this.source === SOURCE_TYPE.CART){
              this.getCartSettlementData(isFromAddAddress)
          }else if(this.source === SOURCE_TYPE.DETAIL){
              this.getDetailSettlementData(isFromAddAddress)
          }else if (this.source === SOURCE_TYPE.SERVICE) {
              this.getServiceSettlementData()
              // this.getUserAddress()
          }
        // if (!this.isrefresher) {
        //   this.loadingIsShow = true
        // }
        // let settlementData = null
        // const asyncTasks = []; // 收集所有需要等待的异步任务
        // if (this.source === SOURCE_TYPE.CART) {
        //   settlementData = this.getCartSettlementData()
        // } else if (this.source === SOURCE_TYPE.DETAIL) {
        //   settlementData = this.getDetailSettlementData()
        // } else if (this.source === SOURCE_TYPE.SERVICE) {
        //   settlementData = this.getServiceSettlementData()
        //   // this.getUserAddress()
        // }
        // asyncTasks.push(settlementData);
        // // 如果是实物商品，额外等待商户数据加载（根据业务逻辑调整条件）
        // if (this.source !== SOURCE_TYPE.SERVICE) {
        //   // 确保地址存在时才等待商户数据
        //   if (this.receivingAddress?.id) {
        //     asyncTasks.push(this.getMerchantList(this.receivingAddress.id));
        //   }
        // }

        //   Promise.all(asyncTasks).then(() => {
        //     console.log('所有api加载完成')
        //     this.loadingIsShow = false
        //     this.loadingIsShowPage = false
        //     // 关闭加载状态 (转动的圈)，需要一点延时才能关闭
        //     this.time = setTimeout(e => {
        //       this.isrefresher = false
        //     }, 200)
        //   }).catch((error) => {
        //       console.error('数据加载失败:', error);
        //       this.loadingIsShow = false;
        //       this.loadingIsShowPage = false;
        //       this.isrefresher = false;
        //       Toast('数据加载失败，请重试'); // 需确保Toast已正确引入
        //   });
      },

      onClickLeft() {
        uni.navigateBack()
      },
      // 下拉选择框
      changeAddress(val) {
        this.house = val
        // this.showHouseName = true
        this.myHouse = true
      },
      // 提示
      // toastMsg() {
      //   Toast('请先选择地址再进行结算')
      // },

      // 关闭修改地址弹窗
      async closeMyHouse(id) {
        console.log('关闭 关闭关闭-------1111')
        this.myHouse = false
        if(id){
            const targetAddress = this.ebUserAddressList.find(item => item.id === id) 
            if(targetAddress) {
                this.receivingAddress = targetAddress;
            }
            await this.getMerchantList(id)
        }
      },

      changeTab(index, e, itemName) {
        this.currentIndex = index
        console.log(index, itemName)
        // this.$emit('sliderSelect', index, itemName)
      },
      scrollPage(e) {
        console.log(e.detail.scrollTop, this.scrolling)
        if (e.detail.scrollTop > 25 && !this.scrolling) {
          this.scrolling = true
        } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
          this.scrolling = false
        }
      },

      // 优惠券
      openMyCoupon() {
        this.myCouponShow = true
      },
      closeMyCoupon() {
        this.myCouponShow = false
      },
      // 确认选择的优惠券
      submitCoupon(selectedCpupon,isChange){
        console.log(selectedCpupon,'关闭优惠券',this.defaultBestCoupon,isChange)
        this.isDefaultSubmit = isChange? 0 :1

        if(!isChange){
          return false
        }

        if(this.defaultBestCoupon.id !== selectedCpupon.id || this.defaultBestCoupon.couponId !==selectedCpupon.couponId){
          this.defaultBestCoupon = selectedCpupon
          const couponParams = {
            selectedCouponId:selectedCpupon.id,
            totalFullDiscount:this.totalFullDiscount,  //总满减金额
            productInfoList:this.couponProductInfoList, //originalProductPrice
            productMatchedCouponInfoList: this.transformCouponRelations()
          }
          console.log(couponParams,'优惠券参数')
          changeCouponAndGetResultApi(couponParams).then(res => {
            if (res.code === 200) {
              console.log(res,'changeCoupon')
              const changeCouponResponse = res?.data || {}
              this.needPayCashAmount = changeCouponResponse.needPayCashAmount || '0' //需要支付的金额
              this.frontCalAmount = changeCouponResponse?.frontCalAmount || '0' //前端计算金额
              
              const useCash = this.needPayCashAmount == '0' || this.needPayCashAmount=='0.00' ? this.frontCalAmount : JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金
              this.useCash = JSON.parse(JSON.stringify(this.needPayCashAmount)); //实际需要支付的现金（除去积分之外的）
              this.popupCash = useCash; //支付方式的选择第一个框  最优的除积分之外最优的固定的现金;

              // 该订单最大可用积分+用户当前拥有的积分   得出可使用的积分  
              const usePoints = Number(this.orderMaxUsefulIntegrals) > 0 ? (Number(this.integralsBalance) >0 && Number(this.integralsBalance) < Number(this.orderMaxUsefulIntegrals)? this.integralsBalance : this.orderMaxUsefulIntegrals):0
              const useIntegrals = this.needPayCashAmount == '0' || this.needPayCashAmount=='0.00' ? this.frontCalAmount * this.exchangeRate :usePoints //实际使用积分数
              this.useIntegrals = JSON.parse(JSON.stringify(useIntegrals));
              this.popupUseIntegrals = this.needPayCashAmount == '0'? this.frontCalAmount * this.exchangeRate :useIntegrals;  //弹窗第一个框固定的积分数
              this.finalOrderAmount = Number(this.needPayCashAmount) == 0 || this.needPayCashAmount=='0.00' ? this.frontCalAmount : Number(this.needPayCashAmount)+ Number(this.popupUseIntegrals)*this.exchangeRate;  //最终订单金额 扣掉满减  去掉优惠

              // this.useIntegrals = JSON.parse(JSON.stringify(this.orderMaxUsefulIntegrals)) || '0'  //实际使用积分数  没修改前是这个
              this.totalReductionAmount = changeCouponResponse.totalReductionAmount  //总减免金额
              this.usedCouponAmount = changeCouponResponse.usedCouponAmount

              const info = JSON.parse(JSON.stringify(this.productInfoList))
              console.log(this.productInfo,'productInfo')
              // this.productInfo = info.map(item => {
              //   // 将字符串类型转换为数字类型匹配接口数据
              //   const pid = item.productId
              //   const attrId = item.productAttrValueId

              //   return {
              //     ...item,
              //     detailApportionCouponAmount : changeCouponResponse.couponDistributedAmountTable?.table[pid]?.[attrId] || '0',//明细优惠券优惠分摊的金额
              //     detailFinalActualAmount :changeCouponResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0', //终极版商品明细使用了多少金额
              //     detailUsedPoints : changeCouponResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0', //明细使用积分
              //     detailPointsForCashAmount : Number(changeCouponResponse.productDeductAmountTable?.table[pid]?.[attrId] ) * this.exchangeRate, //明细使用积分抵现的金额
              //   }
              // }
              // )
             
              this.productInfo.forEach((item, index) => {
                const pid = item.productId
                const attrId = item.productAttrValueId
                item.detailApportionCouponAmount=changeCouponResponse.couponDistributedAmountTable?.table[pid]?.[attrId] || '0'//明细优惠券优惠分摊的金额
                let  afterCouponAmount= changeCouponResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0' //终极版使用优惠券后商品明细使用了多少金额
                item.detailFinalActualAmount=(Number(afterCouponAmount) - Number(item.detailApportionFullDiscountAmount)).toString(), //终极版使用优惠券 满减后商品明细使用了多少金额
                item.detailUsedPoints= changeCouponResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0' //明细使用积分
                item.detailPointsForCashAmount = item.detailUsedPoints * this.exchangeRate //明细使用积分抵现的金额
              })
              console.log(this.productInfo, 'productInfo---')
            }
          })
        }
      },
      // 新增转换方法 获取商品拼配的优惠券id
      transformCouponRelations() {
        const table = this.ebStoreCouponResponse.productAndCouponIdTable.table || {}
        return Object.entries(table).flatMap(([productId, attrs]) =>

          Object.entries(attrs).map(([attrValueId, couponIds]) => ({
            productId: parseInt(productId),
            productAttrValueId: parseInt(attrValueId),
            couponIdList: Array.isArray(couponIds) ? couponIds : []
          }))
        )
      },

      // 支付方式
      openPayment(integralsBalance,orderMaxUsefulIntegrals) {
        console.log(this.shouldShowIntegrals)
        // if (!this.shouldShowIntegrals) {
          if(integralsBalance == '0'){
            Toast('您的积分不足')
            return false
          }
          if(orderMaxUsefulIntegrals == '0'){
            Toast('该订单最大可使用积分为0')
            return false
          }
          
        // }
        this.paymentShow = true
      },


      closePayment() {
        this.paymentShow = false
      },

      // 跳转自提点选择页面
      toSelectPick() {
        // 确保已获取有效地址ID
        const addressId = this.receivingAddress?.id;
        if (!addressId) {
          Toast('请先选择收货地址');
          return;
        }
        const params = {
          userAdderssDefault: this.receivingAddress,
          addressId: addressId,
          foundEleMerchant: this.foundEleMerchant,
          distance: this.distance,
          pageSource:'settlement'
        }
        uni.navigateTo({
          url:
            '/pages/shoppingCart/selfPickupPoint?params=' +
            encodeURIComponent(JSON.stringify(params))
        })
      },


      // 提交实物商品订单 跳转收银页面
      async onClickButton() {
          if (this.isSubmitting) {
            Toast('订单正在提交中，请勿重复提交');
            return Promise.reject('重复提交'); // 确保后续代码不会执行
          }
          clearTimeout(this.debounceTimer);
          // 防抖锁定
          this.isSubmitting = true;
    
          try {
            this.debounceTimer = setTimeout(() => {
              this.isSubmitting = false;
            }, 3000); // 3秒后自动解锁防止死锁

            // 支付类型校验逻辑
            if (this.useIntegrals == '0' && this.useCash == '0') {
              Toast('请选择支付方式');
              return;
            }
            console.log('支付方式', this.payType)
            // 自动推导支付类型（如果用户未显式选择）
            if (!this.payType) {
              this.selectPayType()  // 自动推导支付类型（如果用户未显式选择）
            }
            // 在跳转前添加支付方式验证
            if (!['1', '2', '3'].includes(this.payType)) {
              Toast('请选择有效的支付方式');
              return;
            }

            const apiParams = {
              pointToAmountExceed: this.pointToAmountExceed, //积分抵现金额是否超过商品金额
              isDefaultSubmit: this.isDefaultSubmit, // 是否默认提交的数据(0=不是(修改优惠券，修改积分) 1=是(什么都没修改))
              requestSource: this.source, //请求来源
              wxUserId: this.wxUserBaseInfo.id, //微信用户id
              addressId: this.receivingAddress.id,//地址id
              productInfoList: this.productInfo,//商品信息
              cartIdList: this.source === SOURCE_TYPE.CART ? this.prouductIdList :undefined, //购物车id列表  被选中的
              productType: this.productType, //商品类型
              totalAmount: this.totalAmount, //商品总额
              discountedAmount: this.totalFullDiscount, //优惠活动优惠金额  总满减金额
              couponAmount: this.defaultBestCoupon?.money || null, //优惠券优惠金额
              couponId: this.defaultBestCoupon?.id || null, //使用的优惠券id
              selfPickId: this.foundEleMerchant.id, //自提点id
              actualAmount: this.useCash, //实际支付金额
              actualPoints: String(this.useIntegrals), //实际支付积分
              freightAmount: this.freightAmount, //运费金额
              shippingType: this.currentIndex == 0 ? '1' : '2',  //配送方式
              payType: this.payType,  //支付方式
            }
            console.log('提交订单', apiParams)
            const res = await creatOrderApi(apiParams)
            if (res.code === 200) {
              // 成功提交后立即解锁
              clearTimeout(this.debounceTimer);
              this.isSubmitting = false;
              Toast('下单成功，请支付')
              const params = {}
              params.pageSymbol = 'goods'
              params.orderId = res.data.orderId  //订单id
              params.totalAmount = res.data.payAmount  //订单需支付总金额
              params.orderNo = res.data.orderNo  //订单号
              params.source = this.source
              params.productId = this.productList.length >1 ?this.productList[0].productId : this.params.productId  //商品id
              if (this.payAmount == 0 || this.useCash == 0 || this.useCash == '0.00' || this.payAmount == '0.00') {
                params.payAboutType = 'noMoney'
                params.payPoints = this.useIntegrals
                params.payAmount = this.useCash
                params.paymentMsg ='支付成功'
                params.paymentStatus = 'SUCCESS'
                uni.redirectTo({
                  url:
                    '/pages/payment/paySuccess?params=' +
                    encodeURIComponent(JSON.stringify(params))
                })
                // return false
              } else {
                uni.redirectTo({
                  url:
                    '/pages/payment/cashPage?params=' +
                    encodeURIComponent(JSON.stringify(params))
                })
              }
            }
          } catch (error) {
            Toast('提交失败，请重试');
          } finally {
            clearTimeout(this.debounceTimer);
            this.isSubmitting = false;
          }
      },

      // 提交服务商品订单
      async submitServiceOrder() {
        if (this.isSubmitting) {
            Toast('订单正在提交中，请勿重复提交');
            return Promise.reject('重复提交'); // 确保后续代码不会执行
          }
          clearTimeout(this.debounceTimer);
          // 防抖锁定
          this.isSubmitting = true;
    
          try {
            this.debounceTimer = setTimeout(() => {
              this.isSubmitting = false;
            }, 3000); // 3秒后自动解锁防止死锁

            // 支付类型校验逻辑
            if (this.useIntegrals == '0' && this.useCash == '0') {
              Toast('请选择支付方式');
              return;
            }
            // 自动推导支付类型（如果用户未显式选择）
            if (!this.payType) {
              this.selectPayType()  // 自动推导支付类型（如果用户未显式选择）
            }
            // 在跳转前添加支付方式验证
            if (!['1', '2', '3'].includes(this.payType)) {
              Toast('请选择有效的支付方式');
              return;
            }

            const apiParams = {
              productId:this.serviceProductDetail.productId,
              productName:this.serviceProductDetail.productName,
              productSpecName:this.serviceProductDetail.productSpecName,
              productAttrValueId:this.serviceProductDetail.productAttrValueId,
              buyNum:this.serviceProductDetail.buyNum,
              totalAmount: this.totalAmount, //商品总额
              fullDiscountId: this.serviceFullDiscountId, //服务商品满减id
              fullDiscountAmount: this.totalFullDiscount, //优惠活动优惠金额  总满减金额
              couponId: this.defaultBestCoupon?.id || null, //使用的优惠券id
              couponAmount: this.defaultBestCoupon?.money || '0', //优惠券优惠金额
              payAmount: this.useCash, //实际支付金额
              payPoints: this.useIntegrals, //实际支付积分
              payType: this.payType,  //支付方式
              pointsDeductAmount:this.pointsDeductAmount, //积分抵现金额
            }
            console.log('提交订单', apiParams)
            const res = await createServiceOrderApi(apiParams)
            if (res.code == 200) {
              // 成功提交后立即解锁
              clearTimeout(this.debounceTimer);
              this.isSubmitting = false;
              uni.removeStorageSync('newAddressId');
              Toast('下单成功，请支付')

              const params = {}
              params.orderId = res.data.orderId  //订单id
              params.totalAmount = res.data.payAmount  //订单需支付总金额
              params.orderNo = res.data.orderNo  //订单号
              params.source = this.source
              params.productId = this.serviceProductDetail.productId  //商品id
              if ( this.payAmount == 0 || this.useCash == 0 || this.useCash == '0.00' || this.payAmount == '0.00') {
                 params.pageSymbol = 'serviceGoods'
                  uni.redirectTo({
                    url:
                      '/pages/payment/paySuccess?params=' +
                      encodeURIComponent(JSON.stringify(params))
                  })
                  return false
              }else{
                 params.pageSymbol = 'goods'
                  uni.redirectTo({
                    url:
                      '/pages/payment/cashPage?params=' +
                      encodeURIComponent(JSON.stringify(params))
                  })
              }

            }
          } catch (error) {
            Toast('提交失败，请重试');
          } finally {
            clearTimeout(this.debounceTimer);
            this.isSubmitting = false;
          }
      },

      //导航 地图
      toMap(foundEleMerchant) {
          if (!foundEleMerchant || !this.receivingAddress) {
            Toast('商户信息未加载完成');
            return;
          }
          const params = {
            merchantLocation: {
              latitude: foundEleMerchant.latitude,
              longitude: foundEleMerchant.longitude
            },
            userLocation: {
              latitude: this.receivingAddress.latitude,
              longitude: this.receivingAddress.longitude
            }
          }
          uni.navigateTo({
            url:
              '/pages/shoppingCart/map?params=' +
              encodeURIComponent(JSON.stringify(params))
          })
      },

      //处理地址
      async processAddressInfo(wxUserBaseInfo,addressId) {
          this.wxUserBaseInfo = wxUserBaseInfo || {};
          this.ebUserAddressList = this.wxUserBaseInfo.ebUserAddressList || [];

          let id = ''
          if (this.ebUserAddressList.length > 0) {
            if (addressId) {
              this.receivingAddress = this.ebUserAddressList.find(ele => ele.id === addressId) || this.ebUserAddressList[0];
              id = addressId
            }else{
                this.receivingAddress = this.ebUserAddressList.find(ele => ele.isDefault === true) || this.ebUserAddressList[0]  //默认的用户地址
                id = this.receivingAddress?.id;
            }
            if (id) {
              this.getMerchantList(id)
              // try {
              //   // 调用自提点接口，异常时会被 catch 捕获
              //   await this.getMerchantList(id);
              // } catch (error) {
              //   // 接口报错时主动置空自提点数据
              //   this.merchantList = [];
              //   this.foundEleMerchant = null;
              //   console.error('获取自提点失败，已置空列表:', error);
              // }
            }
          }
          // this.foundEleMerchant = this.merchantList[0] || null;
          // console.log('最终商户数据:', this.foundEleMerchant);
      },

      // 处理商品信息 提交订单时需要的商品信息
      async processProductInfo(responseData) {
          const integralsResponse = responseData?.ebStoreIntegralsResponse || {};
          const fullDiscountMatchedResponse = responseData.fullDiscountMatchedResponse || {};
          const info = JSON.parse(JSON.stringify(this.productInfoList))
          // 映射关键字段到productInfo
          this.productInfo = info.map(item => {
            // 将字符串类型转换为数字类型匹配接口数据
            const pid = item.productId
            const attrId = item.productAttrValueId

            return {
              productId: pid,           // 商品ID
              productName: item.productName,
              productImageUrl: item.productUrl,
              // productImageUrl: item.productAttrValueList?.find(
              //   attr => attr.id === item.productAttrValueId
              // )?.image || item.productUrl, // 商品对应规格图片
              // productType:item.seckillId,  //商品类型
              productAttrValueId: attrId, // 规格ID
              skuName: item.skuName,
              quantity: item.cartNum,
              // storeKind:item.seckillId,
              categoryIdList: item.categoryIdList,

              detailUsedPoints: integralsResponse.productActualUsedPointsTable?.table[pid]?.[attrId] || '0', //明细使用积分
              detailPointsForCashAmount: integralsResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0', //明细使用积分抵现的金额
              originalityDetailAmount: item.price,  //明细消费原始的金额
              detailApportionFullDiscountAmount: (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                .find(d =>
                  d.productId === pid &&
                  d.productAttrValueId === attrId
                )?.bestDiscount || '0', //明细满减活动分摊的金额
              // detailApportionFullDiscountAmount: fullDiscountMatchedResponse.bestDiscount || '0', //明细满减活动分摊的金额
              detailFullDiscountId: (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                .find(d =>
                  d.productId === pid &&
                  d.productAttrValueId === attrId
                )?.bestFullDiscount?.id || null, //明细使用的满减ID
              detailApportionCouponAmount: this.ebStoreCouponResponse.couponApportionmentAmountTable?.table[pid]?.[attrId] || '0', //明细优惠券优惠分摊的金额
              detailFinalActualAmount: integralsResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0', //终极版商品明细使用了多少金额
            }
          }
          )
          console.log(this.productInfo, 'productInfo---')

          // 切换选择优惠券时需要的商品信息
          this.couponProductInfoList = info.map(({ productId, productAttrValueId, cartNum,price }) => ({
            productId: productId,           // 商品ID
            productAttrValueId: productAttrValueId, // 规格ID
            num: cartNum,
            afterFullDiscountProductAmount: fullDiscountMatchedResponse.afterFullDiscountProductAmountsTable?.table[productId]?.[productAttrValueId] || '0', //终极版商品明细使用了多少金额
            originalProductPrice:price || '0'  // 添加商品原始价格
          }))
      },
      // 优惠满减信息
      processPaymentInfo(responseData) {
          this.pointToAmountExceed = responseData.pointToAmountExceed?? 0  //积分抵现金额是否超过商品金额
          // 支付基础信息
          this.needPayCashAmount = responseData.needPayCashAmount ?? '0' // 需要付的现金
          this.frontCalAmount = responseData.frontCalAmount ?? '0' //前端计算金额
          this.integralsBalance = responseData.integralsBalance ?? '0'// 我的账户余额
          this.exchangeRate = responseData.pointsRatio ?? '0'  //兑换率
          this.totalAmount = responseData.totalAmount ?? '0' //商品总金额

          // 积分计算
          this.orderMaxUsefulIntegrals = responseData?.ebStoreIntegralsResponse?.orderMaxUsefulIntegrals ?? 0  //订单最大可用积分数
          // 该订单实际可以用的积分  取得我的积分余额与订单最大可用积分的较小值
          const usePoints = Number(this.orderMaxUsefulIntegrals) > 0 ? (Number(this.integralsBalance) >0 && Number(this.integralsBalance) < Number(this.orderMaxUsefulIntegrals)? this.integralsBalance : this.orderMaxUsefulIntegrals):0
          const useIntegrals = this.needPayCashAmount == '0' || this.needPayCashAmount =='0.00' ? this.frontCalAmount * this.exchangeRate :usePoints //实际使用积分数
          this.useIntegrals = JSON.parse(JSON.stringify(useIntegrals)) || '0'  //实际使用积分数 
         
          this.useCash = JSON.parse(JSON.stringify(this.needPayCashAmount));

          this.popupCash = this.needPayCashAmount == '0' || this.needPayCashAmount =='0.00'? this.frontCalAmount : JSON.parse(JSON.stringify(this.needPayCashAmount));
          this.popupUseIntegrals = this.needPayCashAmount == '0' || this.needPayCashAmount =='0.00'? this.frontCalAmount * this.exchangeRate :useIntegrals;  //弹窗第一个框固定的积分数
          this.finalOrderAmount = Number(this.needPayCashAmount) == 0 || this.needPayCashAmount=='0.00' ? this.frontCalAmount : Number(this.needPayCashAmount)+ Number(this.popupUseIntegrals)*this.exchangeRate;  //最终订单金额 扣掉满减  去掉优惠

          // 优惠信息
          this.totalReductionAmount = responseData.totalReductionAmount ?? '0'  //总减免金额
          const integralsResponse = responseData?.ebStoreIntegralsResponse ?? {}  //积分以及分摊信息
          const fullDiscountMatchedResponse = responseData.fullDiscountMatchedResponse  //满减以及分摊信息
          // this.totalDiscount = fullDiscountMatchedResponse.totalDiscount || '0'  //满减减得部分
          // this.totalDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0'  //满减减得部分
          this.totalThresholdAmount = fullDiscountMatchedResponse.totalThresholdAmount || null
          this.totalFullDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0' //总满减金额
      },
      // 处理商品列表
      processProductList(responseData){
          this.productInfoList = JSON.parse(JSON.stringify(responseData.productAndAttrResponse.responseList));
          this.productList = JSON.parse(JSON.stringify(this.productInfoList));

          this.productList.forEach(item => {
            let productAttrValueName = ''
            let productStock = ''
            // 使用 find 方法找到满足条件的元素
            const foundEle = item.productAttrValueList.find(ele => ele.id === item.productAttrValueId);
            console.log(foundEle, 'foundEle')
            if (foundEle) {
              if (foundEle.suk !== '') {
                productAttrValueName = foundEle.suk  //规格名称
              } else {
                productAttrValueName = '默认' //规格名称
              }
              // productAttrValueName = foundEle.suk  //规格名称
              productStock = foundEle.stock  //规格库存
            }
            item.productAttrValueName = productAttrValueName;
            item.productStock = productStock
          })
      },
      // 处理商品优惠券信息
      processProductCouponList(responseData){
          this.ebStoreCouponResponse = responseData.ebStoreCouponResponse || {} //优惠券信息（可用优惠券+不可用优惠券）
          this.ebStoreCouponList = this.ebStoreCouponResponse?.availableCouponList || [] //用户拥有的可用优惠券列表
          this.defaultBestCoupon = this.ebStoreCouponResponse?.defaultBestEbStoreCoupon || null //默认最优优惠券
      }, 

      // 公共处理方法
      async processSettlementData(data,isFromAddAddress) {
          const responseData = data.response;
          const wxUserBaseInfo = data.wxUserBaseInfo;
          if (!isFromAddAddress) {
            // 处理商品列表
            this.processProductList(responseData);
            // 处理支付信息
            this.processPaymentInfo(responseData);
            this.processProductCouponList(responseData)
            // 处理商品详细信息
            this.processProductInfo(responseData);
          }
          // 处理地址信息
          // await this.processAddressInfo(wxUserBaseInfo)

      },

      /** 
       * 接口测试
       *  */
      async getCartSettlementData(addressId) {
          //  this.loadingIsShow = true; // 开始加载时显示loading
          try {
            const res = await getCartSettlementApi();
            if (res.code === 200) {
              this.loading = false
              console.log(res.data, 'res')
              await this.processSettlementData(res.data,addressId);
              // const responseData = res.data.response
              // this.productInfoList = JSON.parse(JSON.stringify(responseData.productAndAttrResponse.responseList))
              // this.productList = JSON.parse(JSON.stringify(this.productInfoList))
              // this.productList.forEach(item => {
              //   let productAttrValueName = ''
              //   let productStock = ''
              //   // 使用 find 方法找到满足条件的元素
              //   const foundEle = item.productAttrValueList.find(ele => ele.id === item.productAttrValueId);
              //   console.log(foundEle, 'foundEle')
              //   if (foundEle) {
              //     if(foundEle.suk !==''){
              //       productAttrValueName = foundEle.suk  //规格名称
              //     }else{
              //       productAttrValueName = '默认' //规格名称
              //     }
              //     // productAttrValueName = foundEle.suk  //规格名称
              //     productStock = foundEle.stock  //规格库存
              //   }
              //   item.productAttrValueName = productAttrValueName;
              //   item.productStock = productStock
              // })

              // this.needPayCashAmount = responseData.needPayCashAmount ?? '0' // 需要付的现金
              // this.frontCalAmount = responseData.frontCalAmount ?? '0' //前端计算金额
              // this.integralsBalance = responseData.integralsBalance ?? '0'// 我的账户余额
              // this.exchangeRate = responseData.pointsRatio ?? '0'  //兑换率
              // this.totalAmount = responseData.totalAmount ?? '0' //商品总金额

              // this.orderMaxUsefulIntegrals = responseData?.ebStoreIntegralsResponse?.orderMaxUsefulIntegrals ?? 0  //订单最大可用积分数
              // const usePoints = this.orderMaxUsefulIntegrals > 0 ? (this.integralsBalance >0 && this.integralsBalance < this.orderMaxUsefulIntegrals? this.integralsBalance : this.orderMaxUsefulIntegrals):0
              // this.useIntegrals = this.needPayCashAmount == '0' ? this.frontCalAmount * this.exchangeRate :usePoints //实际使用积分数

              // // this.useIntegrals = this.needPayCashAmount == '0' ? this.frontCalAmount * this.exchangeRate :0  //实际使用积分数  以前的
            
              // this.useCash = JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金
              // this.popupCash = this.needPayCashAmount == '0' ? this.frontCalAmount :  JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金

              // this.totalReductionAmount = responseData.totalReductionAmount ?? '0'  //总减免金额
              // const integralsResponse = res.data.response?.ebStoreIntegralsResponse ?? {}  //积分以及分摊信息
              // const fullDiscountMatchedResponse = responseData.fullDiscountMatchedResponse  //满减以及分摊信息
              // // this.totalDiscount = fullDiscountMatchedResponse.totalDiscount || '0'  //满减减得部分
              // // this.totalDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0'  //满减减得部分
              // this.totalThresholdAmount = fullDiscountMatchedResponse.totalThresholdAmount || null
              // this.totalFullDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0' //总满减金额

              // this.ebStoreCouponResponse = responseData.ebStoreCouponResponse || {} //优惠券信息（可用优惠券+不可用优惠券）
              // this.ebStoreCouponList = this.ebStoreCouponResponse?.availableCouponList || [] //用户拥有的可用优惠券列表
              // this.defaultBestCoupon = this.ebStoreCouponResponse?.defaultBestEbStoreCoupon || null //默认最优优惠券


              this.nearestDistanceMap = res.data.nearestDistanceMap || undefined //距离信息
              // this.wxUserBaseInfo = res.data?.wxUserBaseInfo || {}  //微信用户基础信息
              // this.ebUserAddressList = this.wxUserBaseInfo.ebUserAddressList || []  //用户地址
              // if(this.ebUserAddressList.length > 0){
              //   this.receivingAddress = this.ebUserAddressList.find(ele => ele.isDefault === true) || this.ebUserAddressList[0]  //默认的用户地址
              // }
              // const addressId = this.receivingAddress?.id;  //地址id
              // if (addressId) {
              //   await this.getMerchantList(addressId)
              // }
              // // 使用接口返回的最新商户数据
              // this.foundEleMerchant = this.merchantList[0] || null;
              // console.log('最终商户数据:', this.foundEleMerchant);
    
              // const info = JSON.parse(JSON.stringify(this.productInfoList))
              // // 映射关键字段到productInfo
              // this.productInfo = info.map(item => {
              //   // 将字符串类型转换为数字类型匹配接口数据
              //   const pid = item.productId
              //   const attrId = item.productAttrValueId

              //     return {
              //       productId: item.productId,           // 商品ID
              //       productName: item.productName,
              //       productImageUrl: item.productUrl,
              //       // productImageUrl: item.productAttrValueList?.find(
              //       //   attr => attr.id === item.productAttrValueId
              //       // )?.image || item.productUrl, // 商品对应规格图片
              //       // productType:item.seckillId,  //商品类型
              //       productAttrValueId: item.productAttrValueId, // 规格ID
              //       skuName: item.skuName,
              //       quantity: item.cartNum,
              //       // storeKind:item.seckillId,
              //       categoryIdList: item.categoryIdList,

              //       detailUsedPoints: integralsResponse.productActualUsedPointsTable?.table[pid]?.[attrId] || '0', //明细使用积分
              //       detailPointsForCashAmount: integralsResponse.productDeductAmountTable?.table[pid]?.[attrId] || '0', //明细使用积分抵现的金额
              //       originalityDetailAmount: item.price,  //明细消费原始的金额
              //       detailApportionFullDiscountAmount: (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
              //         .find(d =>
              //           d.productId === pid &&
              //           d.productAttrValueId === attrId
              //         )?.bestDiscount || '0', //明细满减活动分摊的金额
              //       // detailApportionFullDiscountAmount: fullDiscountMatchedResponse.bestDiscount || '0', //明细满减活动分摊的金额
              //       detailFullDiscountId:  (fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
              //         .find(d =>
              //           d.productId === pid &&
              //           d.productAttrValueId === attrId
              //         )?.bestFullDiscount.id || null, //明细使用的满减ID
              //       detailApportionCouponAmount: this.ebStoreCouponResponse.couponApportionmentAmountTable?.table[pid]?.[attrId] || '0', //明细优惠券优惠分摊的金额
              //       detailFinalActualAmount: integralsResponse.finalProductDetailAmountTable?.table[pid]?.[attrId] || '0', //终极版商品明细使用了多少金额
              //     }
              //   }
              // )
              // console.log(this.productInfo, 'productInfo')
              // this.couponProductInfoList = info.map(({productId, productAttrValueId, cartNum }) => ({
              //     productId: productId,           // 商品ID
              //     productAttrValueId:productAttrValueId, // 规格ID
              //     num: cartNum,
              //     afterFullDiscountProductAmount: fullDiscountMatchedResponse.afterFullDiscountProductAmountsTable?.table[productId]?.[productAttrValueId] || '0', //终极版商品明细使用了多少金额
              // }) )

            }
          } catch (error) {
            console.error('获取数据失败:', error);
          } finally {
            // this.loadingIsShow = false; // 无论成功失败都隐藏loading
            // this.isrefresher = true
          }
      },

      // 商品详情页面 -- 立即购买
      async getDetailSettlementData(isFromAddAddress) {
          try {
            const pa = {
                productId: this.params.productId,
                productAttrValueId: this.params.productAttrValueId,
                buyNum: this.params.buyNum
            }
            console.log(pa,'pa')
            const res = await directBuyApi(pa);
            if (res.code === 200) {
                // this.loadingIsShow = false; // 无论成功失败都隐藏loading
                console.log(res.data, 'res')
                await this.processSettlementData(res.data,isFromAddAddress);
                this.nearestDistanceMap = res.data.nearestDistanceMap || undefined //距离信息
            }
          } catch (error) {
              console.error('获取数据失败:', error);
          } finally {
              // this.loadingIsShow = false; // 无论成功失败都隐藏loading
              // this.isrefresher = true
          }
      },

      // 获取服务商品结算明细
      async getServiceSettlementData(orderId) {
        //  this.loadingIsShow = true; // 开始加载时显示loading
        try {
            const apiParams = {
                productId: this.params.productId,
                productAttrValueId: this.params.productAttrValueId,
                buyNum: this.params.buyNum
            }
            console.log(apiParams,'pa')
            const res = await queryServiceSettleInfoApi(apiParams);
            if (res.code === 200) {
                // this.loadingIsShow = false; // 无论成功失败都隐藏loading              
                console.log(res.data, 'res')
                this.serviceProductDetail = res?.data?.detail || {} //服务商品详情
                this.nickName = res?.data?.nickName || '微信用户'//当前登录用户昵称
                this.phone = res?.data?.phone || null //当前登录用户手机号
                const productAttrValueId = this.serviceProductDetail?.productAttrValueId
                this.ebStoreCouponResponse = res?.data?.ebStoreCouponResponse || {} //优惠券信息（可用优惠券+不可用优惠券）
                this.ebStoreCouponList = res?.data?.ebStoreCouponResponse?.availableCouponList || [] //用户拥有的可用优惠券列表
                this.defaultBestCoupon = this.ebStoreCouponResponse?.defaultBestEbStoreCoupon || null //默认最优优惠券
                this.needPayCashAmount = res.data?.actualAmount || 0 //需要支付的现金
                this.useCash = JSON.parse(JSON.stringify(this.needPayCashAmount))  //实际支付的现金

                this.integralsBalance = res.data.points ?? '0'// 我的账户余额

                this.orderMaxUsefulIntegrals = res?.data?.detail?.maxUsefulPoints ?? 0  //订单最大可用积分数
                // const usePoints = this.orderMaxUsefulIntegrals > 0 ? (this.integralsBalance >0 && this.integralsBalance < this.orderMaxUsefulIntegrals? this.integralsBalance : this.orderMaxUsefulIntegrals):0
                // const _useIntegrals = Number(res.data.pointsPay) > Number(usePoints) ? usePoints : res.data.pointsPay
                const useIntegrals = res?.data?.pointsPay || 0//实际使用积分数
                this.useIntegrals = JSON.parse(JSON.stringify(useIntegrals))  //实际使用积分数
                const pointsDeductAmount =res?.data?.pointsDeductAmount ||  '0' //积分抵现金额

                this.popupCash = this.needPayCashAmount == '0'|| this.needPayCashAmount == '0.00'? pointsDeductAmount :this.needPayCashAmount;   //弹窗第一个框固定的现金
                console.log(this.popupCash,'this.popupCash---service')
                this.popupUseIntegrals = useIntegrals//弹窗第一个框固定的积分数
                this.finalOrderAmount = this.popupCash + this.popupUseIntegrals * 10  //最终订单金额 扣掉满减  去掉优惠

                const fullDiscountMatchedResponse = res?.data?.fullDiscountMatchedResponse  //满减以及分摊信息
                this.totalThresholdAmount = fullDiscountMatchedResponse.totalThresholdAmount || null
                this.totalFullDiscount = fullDiscountMatchedResponse.totalFullDiscount || '0' //总满减金额
                this.totalAmount = fullDiscountMatchedResponse.totalAmount ?? '0' //商品总金额
                this.totalAdditionalAmount = fullDiscountMatchedResponse.totalAdditionalAmount?? '0' //凑的金额
                this.serviceFullDiscountId=(fullDiscountMatchedResponse.fullDiscountMatchedDetailResponseList || [])
                  .find(d =>
                    d.productId === this.serviceProductDetail.productId &&
                    d.productAttrValueId === productAttrValueId
                  )?.bestFullDiscount?.id || null //明细使用的满减ID
                console.log(this.serviceFullDiscountId,'this.serviceFullDiscountId')
                this.payType = res.data.paymentMethod?? '1'
                this.pointsDeductAmount = res.data.pointsDeductAmount?? '0'

            }
          } catch (error) {
              console.error('获取数据失败:', error);
          } finally {
            // this.loadingIsShow = false; // 无论成功失败都隐藏loading
            // this.isrefresher = true
          }
      },

      // 获取用户地址列表
      async getUserAddressList(newAddressId) {
        return new Promise((resolve, reject) => {
          getUserAddressApi().then(res => {
            console.log(res, '获取用户地址')
            if (res.code == 200) {
              // this.addressList = res.data || []
                this.ebUserAddressList = res?.data || [];
                let id = ''
                if (this.ebUserAddressList.length > 0) {
                  if (newAddressId) {
                    this.receivingAddress = this.ebUserAddressList.find(ele => ele.id === newAddressId) || this.ebUserAddressList[0];
                    id = newAddressId
                  } else {
                    this.receivingAddress = this.ebUserAddressList.find(ele => ele.isDefault === true) || this.ebUserAddressList[0]  //默认的用户地址
                    id = this.receivingAddress?.id;
                  }
                  if (id) {
                    this.getMerchantList(id)
                    // try {
                    //   // 调用自提点接口，异常时会被 catch 捕获
                    //   await this.getMerchantList(id);
                    // } catch (error) {
                    //   // 接口报错时主动置空自提点数据
                    //   this.merchantList = [];
                    //   this.foundEleMerchant = null;
                    //   console.error('获取自提点失败，已置空列表:', error);
                    // }
                  }
                }

                resolve()
            }else{
              this.ebUserAddressList = []
              this.foundEleMerchant = null;
              reject(); // 关键修改：抛出错误
            }
          })
        })
      },
      // 获取商户信息列表
      async getMerchantList(addressId) {
        if (!addressId) {
          console.error('缺少地址ID');
          return false
        }
        try {
          const res = await getMerchantListApi({ pageSize: 10, pageNum: 1, addressId: addressId })
          if (res.code === 200) {
            this.merchantList = res.data.merchantList || [] //商户列表

            this.foundEleMerchant = this.merchantList[0] || null//推荐的自提点
            console.log(this.foundEleMerchant, 'foundEleMerchant')
            const dis = res.data.distance
            this.distance = dis > 1000 ? `${(dis / 1000).toFixed(2)}公里` : `${dis}米`
            //  const dis = Number(res.data.distance) || 0
            //  this.distance = dis >= 1000 ?  `${(dis / 1000).toFixed(dis%1000 === 0 ? 0 : 2)}公里` :  `${Math.round(dis)}米`
      
          }else{
            this.merchantList = []
            this.foundEleMerchant = null
            throw new Error(`获取商户列表失败，错误码：${res.code}`); // 关键修改：抛出错误
          }
        } catch (error) {
          console.error('获取商户失败:', error);
          this.merchantList = []
          this.foundEleMerchant = null;
        }
      },


      //确认支付方式        
      handlePaymentConfirm(data,current) {
        console.log('支付方式:', data.type)
        console.log('使用积分:', data.score)
        console.log('需付现金:', data.cash)
        this.isDefaultSubmit = current==0? 1 : 0
        console.log(this.isDefaultSubmit,'this.isDefaultSubmit',current,'current')

        if (current !== 0) {
          if (this.source !== SOURCE_TYPE.SERVICE) {
            // 积分分摊逻辑
            // 将 data.score 转换为数字类型，如果 data.score 不是有效的数字，则默认为 0
            const totalPoints = Number(data.score) || 0
            const totalCash = String(Number(data.cash)).replace(/(\.0+|(?<=\.\d)0+)$/, '');

            console.log(this.productInfo, 'productInfo', totalPoints, 'totalPoints')
            // 关键修改：检查 productInfo 是否为有效数组
            if (!Array.isArray(this.productInfo) || this.productInfo.length === 0) {
              console.error('商品信息未加载完成，无法分摊积分');
              return; // 或根据业务需求处理错误
            }

            // 计算所有商品的折扣后总金额
            const totalDiscountAmount = this.productInfo.reduce((sum, item) => {
              // 关键修改：确保afterDiscountAmount是有效数字（处理NaN/undefined/null/非数字字符串）
              const fullDiscountAmount = Number(item.detailApportionFullDiscountAmount) || 0;
              const couponAmount = Number(item.detailApportionCouponAmount) || 0;
              return sum + fullDiscountAmount + couponAmount;
            }, 0);

            // 新增：计算原始价格总金额（用于totalDiscountAmount为0时的兜底）
            const totalOriginalAmount = this.productInfo.reduce((sum, item) => {
              const originalAmount = Number(item.originalityDetailAmount) || 0; // 原始价格字段
              return sum + originalAmount;
            }, 0);

            // 计算最终可用的总金额（原始价格减去折扣和优惠券）
            const finalOrderAmount = totalOriginalAmount - totalDiscountAmount;

            console.log(totalDiscountAmount, 'totalDiscountAmount', totalOriginalAmount, 'totalOriginalAmount', finalOrderAmount, 'finalOrderAmount')

            if (this.productInfo.length == 1) {
              // 单个商品：直接分配全部积分
              const singleItem = this.productInfo[0];
              singleItem.detailUsedPoints = String(totalPoints)
              singleItem.detailPointsForCashAmount = String(totalPoints / this.exchangeRate)
              singleItem.detailFinalActualAmount = totalCash

            } else {  //多个商品
              // 初始化剩余积分，初始值为总积分
              let remainingPoints = totalPoints
              let remainingCash = totalCash


              // 积分分配 按照原价格的比例分配  但是积分又不能超过商品的最大可用积分
              this.productInfo.forEach((item, index) => {
                // 获取当前商品在productList中的maxUsefulIntegrals
                const productInList = this.productList.find(p => p.productId == item.productId &&
                  p.productAttrValueId === item.productAttrValueId);
                const maxPointsForItem = productInList ? Number(productInList.maxUsefulIntegrals) : 0;

                // 计算当前商品原价占总原价的比例
                const itemOriginalAmount = Number(item.originalityDetailAmount) || 0;
                const ratio = totalOriginalAmount > 0 ? itemOriginalAmount / totalOriginalAmount : 0;

                // 积分分配（前n-1个商品）
                if (index < this.productInfo.length - 1) {
                  const remainingPrice = Number(item.originalityDetailAmount) -
                    (Number(item.detailApportionFullDiscountAmount) || 0) -
                    (Number(item.detailApportionCouponAmount) || 0)           // 单个商品扣掉优惠券满减后剩余价格
                  const priceBasedPoints = Math.floor(remainingPrice * this.exchangeRate) // 剩余价格对应的积分  

                  let allocatedPoints = Math.floor(totalPoints * ratio); // 向下取整
                  allocatedPoints = Math.min(allocatedPoints, priceBasedPoints, maxPointsForItem); // 取三者中的最小值
                  const roundedPoints = allocatedPoints.toFixed(2);
                  item.detailUsedPoints = roundedPoints.replace(/(\.0+|(?<=\.\d)0+)$/, '');;
                  remainingPoints -= allocatedPoints;
                } else {
                  const points = Number(Math.min(remainingPoints, maxPointsForItem));
                  const roundedPoints = points.toFixed(2);
                  item.detailUsedPoints = roundedPoints.replace(/(\.0+|(?<=\.\d)0+)$/, '');;
                }

                // 积分抵现金额计算  item.detailPointsForCashAmount = String(item.detailUsedPoints / (this.exchangeRate || 1));
                // 积分抵现金额计算，保留两位小数并格式化
                const pointsCashAmount = item.detailUsedPoints / (this.exchangeRate || 1);
                console.log(pointsCashAmount, 'pointsCashAmount')
                const formattedAmount = Number(pointsCashAmount.toFixed(2)).toString();
                console.log(formattedAmount, 'formattedAmount')
                item.detailPointsForCashAmount = formattedAmount.replace(/(\.0+|(?<=\.\d)0+)$/, '');

                const detailFinalDiscountAmount = Number(item.detailApportionFullDiscountAmount) || 0;
                const detailFinalCouponAmount = Number(item.detailApportionCouponAmount) || 0;
                const finalAmount = Number(item.originalityDetailAmount) -
                  Number(detailFinalDiscountAmount) -
                  Number(detailFinalCouponAmount) -
                  Number(item.detailPointsForCashAmount);
                const roundedAmount = finalAmount.toFixed(2);
                item.detailFinalActualAmount = roundedAmount.replace(/(\.0+|(?<=\.\d)0+)$/, '');;
              })

              // 折后价格的比例计算 积分的分摊  但是积分又不能超过商品的最大可用积分
              // this.productInfo.forEach((item, index) => {
              //     // 获取当前商品在productList中的maxUsefulIntegrals
              //     const productInList = this.productList.find(p => p.productId === item.productId &&
              //       p.productAttrValueId === item.productAttrValueId);
              //     const maxPointsForItem = productInList ? Number(productInList.maxUsefulIntegrals) : 0;
              //     // 关键修改：处理totalAmount和当前商品afterDiscountAmount均为0的情况
              //     let ratio = 0;
              //     if (totalDiscountAmount === 0 || Number(this.totalReductionAmount)==0) { // 当折扣后金额均为0时，使用原始价格计算比例

              //       if (totalOriginalAmount > 0 ) {  // 原始价格总和不为0 this.totalAmount !== 0
              //         // 计算原始价格总和
              //         const singleItemAmount = Number(item.originalityDetailAmount)
              //         ratio = singleItemAmount / finalOrderAmount;
              //       } else {
              //         // 极端情况：原始价格总和也为0（如赠品），平均分配或按数量分配（根据业务调整）
              //         ratio = 1 / this.productInfo.length;
              //       }
              //     } else {
              //       const singleItemAmount = Number(item.originalityDetailAmount)- Number(item.detailApportionFullDiscountAmount) + Number(item.detailApportionCouponAmount)
              //       // 正常情况使用折扣后金额计算比例
              //       ratio = Number(singleItemAmount) / finalOrderAmount;
              //     }
              //     // 积分分配（前n-1个商品）
              //     if (index < this.productInfo.length - 1) {

              //         let allocatedPoints = Math.floor(totalPoints * ratio); // 向下取整
              //         // let allocatedPoints = Number((totalPoints * ratio).toFixed(2));
              //         // 确保分配的积分不超过商品的最大可用积分
              //         allocatedPoints = Math.min(allocatedPoints, maxPointsForItem)
              //         // item.detailUsedPoints = Number(allocatedPoints).toFixed(2).toString()

              //         const roundedPoints = allocatedPoints.toFixed(2);
              //         item.detailUsedPoints = roundedPoints.replace(/(\.0+|(?<=\.\d)0+)$/, '');
              //         remainingPoints -= allocatedPoints;

              //         console.log(remainingPoints,'remainingPoints')
              //     } else {
              //         // 最后一个商品分配剩余积分，但不能超过该商品的最大可用积分  最后一个小数点不为0
              //         // item.detailUsedPoints = Number(Math.min(remainingPoints, maxPointsForItem)).toFixed(2).toString()
              //         const points = Number(Math.min(remainingPoints, maxPointsForItem));
              //         const roundedPoints = points.toFixed(2);
              //         item.detailUsedPoints = roundedPoints.replace(/(\.0+|(?<=\.\d)0+)$/, '')
              //         console.log(remainingPoints,'remainingPoints')
              //     }
              //     // 积分抵现金额计算
              //     item.detailPointsForCashAmount =  String(item.detailUsedPoints / (this.exchangeRate || 1))

              //     const detailFinalDiscountAmount = Number(item.detailApportionFullDiscountAmount) || 0;
              //     const detailFinalCouponAmount = Number(item.detailApportionCouponAmount) || 0;
              //     const finalAmount = Number(item.originalityDetailAmount) -
              //       Number(detailFinalDiscountAmount) -
              //       Number(detailFinalCouponAmount) -
              //       Number(item.detailPointsForCashAmount);
              //     const roundedAmount = finalAmount.toFixed(2);  
              //     item.detailFinalActualAmount = roundedAmount.replace(/(\.0+|(?<=\.\d)0+)$/, '');
              //       // // 现金分配（前n-1个商品）
              //       // if (index < this.productInfo.length - 1) {
              //       //     const allocatedCash = Number((totalCash * ratio).toFixed(2));
              //       //     item.detailFinalActualAmount = String(allocatedCash)
              //       //     remainingCash -= allocatedCash;
              //       // } else {
              //       //     item.detailFinalActualAmount = String(remainingCash.toFixed(2))
              //       // }
              // })

              // // 遍历每个商品信息
              // this.productInfo.forEach((item, index) => {
              //   // 最后一个商品使用尾插法处理剩余积分
              //   if (index === this.productInfo.length - 1) {
              //     // 将剩余的积分全部分配给最后一个商品
              //     item.detailUsedPoints = remainingPoints
              //     // 根据积分兑换率计算该商品使用积分可抵扣的现金金额
              //     item.detailPointsForCashAmount = item.detailUsedPoints / this.exchangeRate
              //   } else {
              //     // 按比例分配积分
              //     // 计算当前商品的折扣后金额占总金额的比例
              //     const ratio = item.afterDiscountAmount / totalAmount;
              //     // 按比例分配积分给当前商品，并向下取整
              //     item.detailUsedPoints = Math.floor(totalPoints * ratio);
              //     // 减去已分配给当前商品的积分，更新剩余积分
              //     remainingPoints -= item.detailUsedPoints;
              //     // 根据积分兑换率计算该商品使用积分可抵扣的现金金额
              //     item.detailPointsForCashAmount = item.detailUsedPoints / this.exchangeRate
              //   }
              // })
            }
          }
        }

        // 提交支付请求...
        this.useIntegrals = data.score
        this.useCash = String(Number(data.cash)).replace(/(\.0+|(?<=\.\d)0+)$/, '');

        console.log(this.useIntegrals,this.useCash,this.popupCash,this.popupUseIntegrals,'this.useIntegrals',this.productInfo,'this.productInfo')
        // this.popupCash = data.cash
        // 确保金额不会出现负数
        if (Number(this.useCash) < 0) {
          this.useCash = 0;
          Toast('支付金额异常，已重置为纯现金支付');
        }

        this.selectPayType()
      },

      // 积分划分（未选择支付方式时）
      integralsDivision() {
        // 自动分配积分逻辑
        if (!this.payType) {
          // 取三者最小值：积分余额、订单最大积分、现金换算积分
          const maxIntegrals = Math.min(
            this.integralsBalance,
            this.orderMaxUsefulIntegrals,
            Math.floor(this.popupCash * this.exchangeRate)
          );

          this.useIntegrals = maxIntegrals;  //最大可兑换积分
          this.useCash = this.needPayCashAmount == '0'?  this.needPayCashAmount:( this.needPayCashAmount - (maxIntegrals / this.exchangeRate))

          // 确保现金不为负数
          if (this.useCash < 0) {
            this.useCash = 0;
            this.useIntegrals = Math.floor(this.needPayCashAmount * this.exchangeRate);
          }

          // 自动设置支付类型
          this.selectPayType()
        }
      },

      selectPayType() {
        console.log(this.useIntegrals,this.useCash,Number(this.useIntegrals) == 0,Number(this.useCash)== 0)
        // 自动设置支付类型
        if (Number(this.useIntegrals) == 0 || this.useIntegrals == '0.00') {
          this.payType = '1' // 'cash'
        } else if (Number(this.useCash)== 0 || this.useCash == '0.00') {
          this.payType = '2'  // 'point'
        } else if (Number(this.useIntegrals) > 0 && Number(this.useCash) > 0) {
          this.payType = '3' // 'cash_point'
        }
      },



      formatNumber(value) {
        return Number(value).toLocaleString();
      },
      formatCurrency(value) {
        return Number(value).toFixed(2);
      },

    }

}
</script>
<style lang="scss" scoped>

.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    height: 100vh;
    overflow: hidden;
    z-index: -2;
    background-color: #FFFFFF;
}

.bgCart{
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background-color: #f9f9f9;
  height: 100vh;
}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}
.cartTop {
  background-color: #ffffff;
  padding-left: 24px;
  padding-right: 24px;
  padding-top: 25px;

  // 页面标题部分
  .cartAd {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .cartAd_title {
    font-size: 30px;
    text-align: left;
    line-height: 30px;
    color: #111111;
  }
  .userInfo{
    margin-top: 25px;
    display: flex;
    justify-content: space-between;
    padding-bottom: 23px;

  }
  .userInfo_left{   //左边用户信息
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    width: 68%;
  }

  // .user_address{  //住址
  //   font-size: 14px;
  //   text-align: left;
  //   color: #737373;
  //   white-space: nowrap;
  // }
  // .user_address text{
  //   white-space: nowrap;
  //   /* 防止文本换行 */
  //   overflow: hidden;
  //   /* 超出部分隐藏 */
  //   text-overflow: ellipsis;
  //   /* 显示省略号 */
  // }
    .user_address {
      //住址
      font-size: 28rpx;
      text-align: left;
      color: #737373;
      max-width: 100%;
      display: flex;
      align-items: center;
      //justify-content: space-between;
    }
  
    .user_address_text {
      max-width: 90%;
      white-space: nowrap;
      /* 防止文本换行 */
      overflow: hidden;
      /* 超出部分隐藏 */
      text-overflow: ellipsis;
      /* 显示省略号 */
    }
  .userInfo_bottom{
    font-size: 14px;
    text-align: left;
    color: #737373;
    line-height: 14px;
    margin-top: 13px;

  }
  .userInfo_right{
    float: right;
    text-align: right;
  }

}

// 配送方方式
.tab-bar{
    padding:0px 2px;
    height: 20px;
    background: #F0F0F0;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}


//自提  同城配送
.gray{
  // padding:2px;
  height: 20px;
  border-radius: 10px;
  .tabbar-item {
      flex: auto;
      z-index: 1;
      height: 20px;
      line-height: 20px;
      text-align: center;
      padding: 0px 3px;
      font-size: 12px;
      color: #111111;

    &.active {
        background: #FF6203;
        border-radius: 10px;
        padding: 0px 18rpx;
        color: #ffffff;
    }

  }
}

// 标题下面的横线
.line {
  height: 9px;
  width: 100%;
  background: #f9f9f9;

}

// 自提点
.self-pickup{
  margin-top: 10px;
  padding: 24px;
  background-color:#FFFFFF;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
// 有自提点的内容
.self-pickup-left{
  width: 75%;
  display: flex;

  .self_pickup_pic{
    width: 20%;
    display: flex;
    flex-direction: column;
    justify-content: center;

    img{
      width: 100%;
        height: auto;
    }
  }

  // 图片右边的文字
    .self_pickup_left_l {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 70%;
      margin-left: 15px;

      .left_top {
        font-size: 22rpx;
        text-align: left;

        .self_pickup_name {
          color: #111111;
          margin-right: 7px;
        }

        .distance {
          color: #FF6203;
        }
      }

      .left_bottom {
        margin-top: 20rpx;
        font-size: 22rpx;
        text-align: left;
        color: #737373 ;
      }
    }

}

.self-pickup-right {
  display: flex;

  .spr_text {
    margin-left: 16rpx;
    font-size: 22rpx;
    text-align: left;
    color: #888888;
  }
}
// 无自提点
.no-self-pickup{
  font-weight: bolder;
  font-size:28rpx;
  text-align: left;
  color: #FF6203;
}

// 同城配送
.city_delivery_content {
    display: flex;
    align-items: center;

    .city_delivery_content_left {
        display: flex;
        // justify-content: space-between;
        flex-direction: column;

        .left_top {
            // flex: auto;
            font-size: 28rpx;
            line-height: 28rpx;
            text-align: left;
        }

        .left_bottom {
            font-size: 22rpx;
            line-height: 22rpx;
            text-align: left;
            color: #737373;
            margin-top: 22rpx;
        }
    }

    .city-delivery {
        .city_delivery_pic {
            width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;

            img {
                width: 100%;
                height: auto;
            }
        }
    }
}

.cartList{
  padding: 24px;
  width: calc(100% - 48px);
  background-color: #ffffff;
}

.goodsWraper {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 15px;
}
.goodsWraper:last-child{
  margin-bottom: 0px;
}

.wraper_left {
  display: flex;
  width: 100%;

  .goodsPic {
    width: 212rpx;
    height: 212rpx;
    overflow: hidden; /* 隐藏超出部分 */
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    img {
      // width: 100%;
      // height: 212rpx;
      width: 100%;
      height: 100%;
      object-fit: cover;
      /* 关键：裁剪图片而不是压缩 */
      object-position: center center; /* 可以调整为 top, bottom 等 */
    }
  }

  .goodsText {
    width: calc(100% - 232rpx);
    padding-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding-top: 12rpx;
    padding-bottom: 12rpx;
    text-align: left;

    .goodsTop {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .goods_T {
          font-size: 28rpx;
          text-align: left;
          color: #111111;
          max-width: 80%;
          line-height: 28rpx;
          // margin-top: 9px;  //display：flex   中 元素居中
          white-space: nowrap;
          /* 防止文本换行 */
          overflow: hidden;
          /* 超出部分隐藏 */
          text-overflow: ellipsis;
          /* 显示省略号 */

        }

        // 商品价格
        .goods_price {
          font-size: 28rpx;
          color: #111111;
          line-height:28rpx;
        }
      }
    .goods_specs {
      margin-top: 24rpx;
      max-width: 80%;
      font-size: 22rpx;
      text-align: left;
      color: #666666;
      min-height: 50rpx;
      display: -webkit-box;
			-webkit-line-clamp: 2;
       /* 标准方案（未来可能支持） */
      line-clamp: 2; /* 标准属性，部分浏览器已支持 */
			-webkit-box-orient: vertical;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: normal;
    }

    .goodsBottom {
        display: flex;
        align-items: center;
        width: 100%;

        .money {
          font-size: 24rpx;
          text-align: left;
          color: #737373;
          // line-height: 24rpx;
        }

        .jifen_box {
          display: flex;
          align-items: center;
          font-size: 24rpx;
          text-align: left;
          // color: #111111;
          color: #737373;
          // line-height: 24rpx;
          height: 24rpx;
          margin-left: 6px;
        }
    }
  }
}

.wraper_right {
  font-size: 22rpx;
  color: #666666;
  width: 10%;
  text-align: right;
}

//防止父元素高度塌陷
.clearfix::before
.clearfix::after {
    content: "";
    display: table;
    clear: both;
}

.line_two{
  height: 5px;
  width: 100%;
  background: #f9f9f9;
  line-height: 5px;
}

// 价格明细
.price_detail {
  // padding: 24px;
  background-color: #ffffff;
  margin-top: 10px;
  padding: 24px 24px 75px 24px;

  .price_detail_content {
    border-bottom: 1px solid #f9f9f9;
    padding-bottom: 20px;
  }

  .price_detail_title {
    font-size: 40rpx;
    text-align: left;
    color: #111111;
  }

  .price_detail_box {
    margin-top: 17px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .num {
    font-size: 28rpx;
    text-align: right;
    color: #111111;
  }

  .num_o {
    font-size: 28rpx;
    text-align: right;
    color: #FF6203;
  }

  // 支付方式
  .payment {
    padding: 20px 0px;
    margin-bottom: 40px;
    // display: flex;
    // justify-content: space-between;

    // padding-bottom: 100px;
  }
    .payment_top {
      display: flex;
      justify-content: space-between;
      align-items: center;
  
      .payment_left,.payment_right {
        font-weight: bolder;
      }
      .payment_right {
        display: flex;
        align-items: center;
      }
    }
}

// 需要支付的积分+金额
.payment_num {
  font-weight: bolder;
  display: flex;
  align-items: center;
  font-size: 32rpx;
  color: #111111;
}
// 很多地方字体 颜色公用
.price_detail_name{
  font-size: 28rpx;
  text-align: left;
  color: #111111;
}
// 运费部分
.price_detail_text{
  font-size: 28rpx;
  text-align: right;
  color: #111111;
}
.price_detail_tips{
  font-size: 24rpx;
  text-align: left;
  color: #666666;
  margin-top: 10rpx;
}

.checked-img {
    height: 16px;
    width: 16px;
}

::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .van-icon {
    color: #242629 !important;
}


::v-deep .van-nav-bar__title {
    font-size: 28rpx;
    color: #333333;
}


::v-deep .van-button--warning{
  background-color: #FF6203;
}

::v-deep .van-icon-success{
  color: #ffffff !important;
}

::v-deep .van-submit-bar__bar{
  display: flex;
  justify-content: space-between !important;
  border-top: 1px solid #f9f9f9;
  height: 72px !important;
  line-height: 72px !important;
}

::v-deep .disabledSubmit .van-button--danger, .van-button--disabled, .van-button--unclickable{
  background-color: #D4D4D4 !important;
  border: 1rpx solid #D4D4D4 !important;
}

// 向右的箭头
.van-icon-arrow{
  color: #666666 !important;
}
</style>
